package huyaoying.study.nio.example;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * 示例的客户端，实时获取服务端时间
 *
 * @author huyaoying
 * @date 2022/2/8
 */
public class TimeQuery {
    // 定义端口
    private static int port = 8125;

    // 定义字符集
    private static Charset charset = Charset.forName("US-ASCII");
    private static CharsetDecoder decoder = charset.newDecoder();

    // 缓冲区
    private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024);

    /**
     * 查询
     *
     * @param host 宿主
     * @throws IOException ioexception
     */
    private static void query(String host) throws IOException {
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
        SocketChannel sc = null;

        try {

            // Connect
            sc = SocketChannel.open();
            sc.connect(isa);

            // Read the time from the remote host. For simplicity we assume
            // that the time comes back to us in a single packet, so that we
            // only need to read once.
            dbuf.clear();
            sc.read(dbuf);

            // Print the remote address and the received time
            dbuf.flip();
            CharBuffer cb = decoder.decode(dbuf);
            System.out.print(isa + " : " + cb);

        } finally {
            // Make sure we close the channel (and hence the socket)
            if (sc != null) {
                sc.close();
            }
        }
    }

    /**
     * 主要
     *
     * @param args arg游戏
     * @throws UnknownHostException 未知主机异常
     */
    public static void main(String[] args) throws UnknownHostException {

        String host = InetAddress.getLocalHost().getHostAddress();
        System.out.println("Connect to Host:" + host + ", port:" + port);
        try {
            query(host);
        } catch (IOException x) {
            System.err.println(host + ": " + x);
        }
    }

}
